import React from 'react';
import DraggerUpload from './DraggerUpload';
import ImageViewer from '@/components/Viewers/ImageViewer';

export default class ImagesUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      images: props.fileList
        ? props.fileList.map(f => ({
            uid: f.uid,
            alt: f.name,
            src: f.url,
          }))
        : [],
    };
  }

  handlePreview = file => {
    const { images } = this.state;
    let index = 0;
    images.forEach((f, i) => {
      if (f.uid === file.uid) index = i;
    });
    this.setState({
      visible: true,
      index,
    });
  };

  handleChange = ({ file, fileList }) => {
    const { onChange } = this.props;
    if (file.status === 'done' || file.status === 'removed') {
      const images = fileList
        .filter(f => f.status === 'done')
        .map(f => ({
          uid: f.uid,
          alt: f.name,
          src: f.url || URL.createObjectURL(f.originFileObj),
        }));
      this.setState({ images });
    }
    if (onChange) onChange({ file, fileList });
  };

  handleClose = () => {
    this.setState({
      visible: false,
    });
  };

  render() {
    const { uploader, viewer, value, ...uploadProps } = this.props;
    const { visible, images, index } = this.state;

    const Upload = uploader || DraggerUpload;
    const Viewer = viewer || ImageViewer;
    return (
      <div>
        <Upload
          {...uploadProps}
          accept="image/*"
          listType="picture-card"
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        />
        <Viewer visible={visible} images={images} activeIndex={index} onClose={this.handleClose} />
      </div>
    );
  }
}
